package com.hcms.common.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import com.hcms.common.service.IOssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;

public class LocalStorageServiceImpl implements IOssService {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String uploadObject(MultipartFile multipartFile) throws IOException {
        logger.info("Upload a file to the local storage");
        String originalFilename = multipartFile.getOriginalFilename();
        if (originalFilename != null) {
            logger.info("Upload object original filename: " + originalFilename);
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String classPath = ResourceUtils.getURL("classpath:").getPath();
            String relativePath = "static/upload/" + DateUtil.format(new Date(), "yyyyMMdd/");
            String sha1 = SecureUtil.sha1(multipartFile.getInputStream());
            String newName = sha1 + fileSuffix;
            File basePath = new File(classPath, relativePath);
            if (!basePath.exists()) {
                logger.info("Create directory: {}", basePath.getAbsolutePath());
                basePath.mkdirs();
            }
            File newFile = new File(basePath, newName);
            multipartFile.transferTo(newFile);
            logger.info("New file path: {}", newFile.getAbsolutePath());
            return relativePath + newName;
        } else {
            logger.error("The original file does not exist");
        }
        return null;
    }

    @Override
    public boolean deleteObject(String url) throws FileNotFoundException {
        String classPath = ResourceUtils.getURL("classpath:").getPath();
        File file = new File(classPath, url);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }

}
